<template>
  <div class="project-view">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>My Project</h3>
          <div class="actions">
            <el-input
                v-model="searchQuery"
                placeholder="Search Project"
                prefix-icon="el-icon-search"
                clearable
                class="search-input"
                @input="handleSearch"
            />
            <el-button @click="navigateToChat" type="success">
              <el-icon><ChatDotRound /></el-icon>
              <span>Contact Supervisor</span>
            </el-button>
            <el-button type="primary" @click="openApplyProjectDialog">Apply Project</el-button>
          </div>
        </div>
      </template>

      <el-table
          :data="filteredProjects"
          border
          style="width: 100%"
          v-loading="loading"
          max-height="650px"
          :key="tableKey"
      >
        <el-table-column prop="title" label="Project Title" min-width="200" />
        <el-table-column prop="category" label="Category" width="120" />
        <el-table-column prop="status" label="Status" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ translateStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="Start Time" width="160" />
        <el-table-column prop="endTime" label="End Time" width="160" />
        <el-table-column label="Actions" width="120" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewProjectDetails(scope.row)">
              <el-icon><View /></el-icon>Details
            </el-button>
          </template>
        </el-table-column>

        <template #empty>
          <div class="empty-data">
            <el-empty description="No project assigned to you" :image-size="120">
              <template #description>
                <p>There are no projects assigned to you at the moment.</p>
                <p class="sub-text">You can click the "Apply Project" button to apply for a project, or wait for the supervisor to assign one.</p>
              </template>
            </el-empty>
          </div>
        </template>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalProjects"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- Project Details Dialog -->
    <el-dialog
        v-model="detailsDialogVisible"
        title="Project Details"
        width="70%"
        destroy-on-close
        @closed="handleProjectDialogClosed"
    >
      <el-descriptions
          v-if="currentProject"
          :column="2"
          border
      >
        <el-descriptions-item label="Project Title" :span="2">{{ currentProject.title }}</el-descriptions-item>
        <el-descriptions-item label="Project Status">
          <el-tag :type="getStatusType(currentProject.status)">
            {{ translateStatus(currentProject.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="Category">{{ currentProject.category || 'Uncategorized' }}</el-descriptions-item>
        <el-descriptions-item label="Start Time">{{ currentProject.startTime || 'Not Set' }}</el-descriptions-item>
        <el-descriptions-item label="End Time">{{ currentProject.endTime || 'Not Set' }}</el-descriptions-item>
        <el-descriptions-item label="Project Description" :span="2">
          <div class="project-description">{{ currentProject.description || 'No description' }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="Project Requirements" :span="2">
          <div class="project-requirements">{{ currentProject.requirements || 'No special requirements' }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="Reference Resources" :span="2">
          <div class="project-resources">{{ currentProject.resources || 'No reference resources' }}</div>
        </el-descriptions-item>
      </el-descriptions>

      <!-- Project Evaluation Section -->
      <div v-if="currentProject && (currentProject.status === 'Completed' || currentProject.status === 'Waiting for Review')" class="project-evaluation-section">
        <div class="section-header">
          <h3>Supervisor Evaluation</h3>
        </div>
        <div v-loading="evaluationLoading">
          <el-empty v-if="!currentEvaluation" description="No Evaluation" :image-size="80">
            <template #description>
              <p>The supervisor has not evaluated this project yet.</p>
            </template>
          </el-empty>

          <div v-else class="evaluation-container">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="score-container" :class="getScoreClass(currentEvaluation.score)">
                  <div class="score-value">{{ currentEvaluation.score }}</div>
                  <div class="score-label">Score</div>
                  <el-progress
                      :percentage="currentEvaluation.score"
                      :color="getScoreColor(currentEvaluation.score)"
                      :format="() => currentEvaluation.score + ' points'"
                      class="score-progress"
                  />
                </div>
              </el-col>
              <el-col :span="16">
                <el-card shadow="hover" class="comment-card">
                  <template #header>
                    <div class="comment-header">
                      <span>Comment</span>
                      <el-tag size="small" type="info">{{ currentEvaluation.evaluationTime }}</el-tag>
                    </div>
                  </template>
                  <div class="comment-content">
                    {{ currentEvaluation.comment || 'The supervisor did not leave a comment' }}
                  </div>
                  <div class="evaluator-info">
                    <el-tag size="small" type="success">Evaluator: {{ currentEvaluation.evaluatorName }}</el-tag>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>

      <!-- Related Tasks List -->
      <div v-if="currentProject" class="related-tasks">
        <h3>Related Tasks
          <el-tooltip content="Refresh task list" placement="top">
            <el-button type="primary" size="small" icon="Refresh" circle plain @click="refreshProjectTasks" :loading="tasksLoading"></el-button>
          </el-tooltip>
        </h3>

        <!-- Tasks Loading State -->
        <div v-if="tasksLoading" class="loading-container">
          <el-skeleton :rows="3" animated />
        </div>

        <!-- Tasks Loading Error -->
        <div v-else-if="tasksLoadError" class="error-container">
          <el-empty description="Error loading tasks">
            <template #description>
              <p>{{ tasksLoadError }}</p>
              <el-button type="primary" @click="refreshProjectTasks">Retry</el-button>
            </template>
          </el-empty>
        </div>

        <!-- No Tasks -->
        <div v-else-if="projectTasks.length === 0" class="empty-task">
          <el-empty description="No related tasks" />
        </div>

        <!-- Tasks List -->
        <el-table v-else :data="projectTasks" border style="width: 100%">
          <el-table-column prop="title" label="Task Title" min-width="200" />
          <el-table-column label="Task Status" width="120">
            <template #default="scope">
              <el-tag :type="getTaskProgressType(scope.row)">
                {{ translateStatus(getTaskProgressStatus(scope.row)) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="Due Time" width="160">
            <template #default="scope">
              <span>{{ scope.row.endTime || 'Not Set' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="Progress" width="160">
            <template #default="scope">
              <div class="progress-icon-container">
                <el-icon v-if="calculateTaskProgress(scope.row) > 0" class="progress-icon completed" style="font-size: 20px; color: #67C23A;">
                  <Check />
                </el-icon>
                <el-icon v-else class="progress-icon not-started" style="font-size: 20px; color: #909399;">
                  <Close />
                </el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="Assignment Status" width="120">
            <template #default="scope">
              <el-tag v-if="isTaskAssignedToMe(scope.row)" type="success" size="small">
                Assigned to me
              </el-tag>
              <el-tag v-else type="info" size="small">
                Other student
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="Actions" width="180">
            <template #default="scope">
              <el-button 
                  type="primary" 
                  size="small" 
                  @click="viewTaskDetails(scope.row)"
                  :disabled="hasEvaluation(scope.row)"
                  :title="hasEvaluation(scope.row) ? 'This task has been evaluated already' : ''"
              >
                Details
              </el-button>
              <el-button
                  type="success"
                  size="small"
                  @click="uploadTaskFile(scope.row)"
                  :disabled="!isTaskAssignedToMe(scope.row) || hasEvaluation(scope.row) || currentProject?.status === 'Review Rejected' || currentProject?.status === 'Waiting for Review'"
                  :title="!isTaskAssignedToMe(scope.row) ? 'You can only upload tasks assigned to you' : hasEvaluation(scope.row) ? 'This task has been evaluated already' : currentProject?.status === 'Review Rejected' ? 'Cannot upload files for project in Review Rejected status' : currentProject?.status === 'Waiting for Review' ? 'Cannot upload files for project in Waiting for Review status' : ''"
              >
                Upload
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailsDialogVisible = false">Close</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
        v-model="taskDialogVisible"
        title="Task Details"
        width="60%"
        destroy-on-close
    >
      <el-descriptions
          v-if="currentTask"
          :column="2"
          border
      >
        <el-descriptions-item label="Task Title">{{ currentTask.title || 'No Title' }}</el-descriptions-item>
        <el-descriptions-item label="Task Status">
          <el-tag :type="getTaskStatusType(currentTask.status || 'Not Started')">
            {{ translateStatus(currentTask.status || 'Not Started') }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="Progress Status">
          <el-tag :type="getTaskProgressType(currentTask)">
            {{ translateStatus(getTaskProgressStatus(currentTask)) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="Progress">
          <div class="progress-icon-container">
            <el-icon v-if="calculateTaskProgress(currentTask) > 0" class="progress-icon completed" style="font-size: 20px; color: #67C23A;">
              <Check />
            </el-icon>
            <el-icon v-else class="progress-icon not-started" style="font-size: 20px; color: #909399;">
              <Close />
            </el-icon>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="Supervisor">{{ currentTask.supervisorName || 'Not Assigned' }}</el-descriptions-item>
        <el-descriptions-item label="Priority">
          <el-tag :type="getPriorityType(currentTask.priority || 'Medium')">
            {{ translateStatus(currentTask.priority) || 'Medium' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="Start Time">{{ currentTask.startTime || 'Not Set' }}</el-descriptions-item>
        <el-descriptions-item label="Due Time">{{ currentTask.endTime || 'Not Set' }}</el-descriptions-item>
        <el-descriptions-item label="Task Description" :span="2">
          <div class="task-description">{{ currentTask.description || 'No description' }}</div>
        </el-descriptions-item>
      </el-descriptions>
      <div class="file-upload-section">
        <div class="section-header">
          <h3>Submit File</h3>
        </div>
        <el-upload
            class="upload-demo"
            :action="`/api/user/tasks/${currentTask?.id}/submit`"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :disabled="!isTaskAssignedToMe(currentTask) || currentProject?.status === 'Review Rejected' || currentProject?.status === 'Waiting for Review'"
        >
          <el-button type="primary" :disabled="!isTaskAssignedToMe(currentTask) || currentProject?.status === 'Review Rejected' || currentProject?.status === 'Waiting for Review'">Click to Upload</el-button>
          <template #tip>
            <div class="el-upload__tip">
              Supports any file type, up to 50MB in size.
            </div>
          </template>
        </el-upload>
      </div>

      <div v-if="submissions.length > 0" class="submission-list">
        <h3>Submitted Files</h3>
        <el-table :data="submissions" border style="width: 100%">
          <el-table-column prop="originalFilename" label="File Name" min-width="200" />
          <el-table-column prop="fileSize" label="Size" width="120">
            <template #default="scope">
              {{ formatFileSize(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column prop="submissionTime" label="Submission Time" width="160" />
          <el-table-column label="Actions" width="180">
            <template #default="scope">
              <el-button type="primary" size="small" @click="downloadSubmission(scope.row)">
                Download
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteSubmission(scope.row)">
                Delete
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="taskDialogVisible = false">Close</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
        v-model="uploadDialogVisible"
        title="Upload File"
        width="50%"
        destroy-on-close
    >
      <div v-if="currentTask" class="task-info-summary">
        <p><strong>Task Title:</strong> {{ currentTask.title }}</p>
        <p>
          <strong>Progress:</strong>
          <el-tag size="small" :type="getTaskStatusType(currentTask.status)">
            {{ translateStatus(currentTask.status) }}
          </el-tag>
        </p>
        <p><strong>Due Time:</strong> {{ currentTask.endTime || 'Not Set' }}</p>
      </div>

      <div class="file-upload-section upload-centered">
        <el-upload
            class="upload-demo"
            :action="`/api/user/tasks/${currentTask?.id}/submit`"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            drag
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            Drag files here or <em>Click to Upload</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              Supports any file type, up to 50MB in size.
            </div>
          </template>
        </el-upload>
      </div>

      <div v-if="submissions.length > 0" class="submission-list">
        <h3>Submitted Files</h3>
        <el-table :data="submissions" border style="width: 100%">
          <el-table-column prop="originalFilename" label="File Name" min-width="200" />
          <el-table-column prop="fileSize" label="Size" width="120">
            <template #default="scope">
              {{ formatFileSize(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column prop="submissionTime" label="Submission Time" width="160" />
          <el-table-column label="Actions" width="180">
            <template #default="scope">
              <el-button type="primary" size="small" @click="downloadSubmission(scope.row)">
                Download
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteSubmission(scope.row)">
                Delete
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">Close</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
        v-model="applyProjectDialogVisible"
        title="Apply Project"
        width="60%"
        destroy-on-close
    >
      <el-form
          ref="projectFormRef"
          :model="projectForm"
          :rules="projectRules"
          label-width="100px"
      >
        <el-form-item label="Project Title" prop="title">
          <el-input v-model="projectForm.title" placeholder="Please enter project title" />
        </el-form-item>
        <el-form-item label="Project Category" prop="category">
          <el-input v-model="projectForm.category" placeholder="Please enter project category" />
        </el-form-item>
        <el-form-item label="Time Range" prop="timeRange">
          <div style="display: flex; gap: 10px; align-items: center;">
            <el-date-picker
                v-model="projectForm.startTime"
                type="datetime"
                placeholder="Start Time"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="new Date(2000, 0, 1, 9, 0, 0)"
                style="width: 100%;"
                :disabled-date="disablePastDates"
                @change="validateProjectTimeRange"
            />
            <span>to</span>
            <el-date-picker
                v-model="projectForm.endTime"
                type="datetime"
                placeholder="End Time"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="new Date(2000, 0, 1, 18, 0, 0)"
                style="width: 100%;"
                :disabled-date="disableBeforeProjectStartDate"
                @change="validateProjectTimeRange"
            />
          </div>
        </el-form-item>
        <el-form-item label="Project Description" prop="description">
          <el-input
              v-model="projectForm.description"
              placeholder="Please enter project description"
              type="textarea"
              :rows="4"
          />
        </el-form-item>
        <el-form-item label="Project Requirements" prop="requirements">
          <el-input
              v-model="projectForm.requirements"
              placeholder="Please enter project requirements"
              type="textarea"
              :rows="4"
          />
        </el-form-item>
        <el-form-item label="Expected Outcomes" prop="resources">
          <el-input
              v-model="projectForm.resources"
              placeholder="Please enter expected outcomes"
              type="textarea"
              :rows="3"
          />
        </el-form-item>
        <el-form-item label="Supervisor" prop="supervisorId" required>
          <el-select v-model="projectForm.supervisorId" placeholder="Please select a supervisor" filterable>
            <el-option
                v-for="supervisor in supervisors"
                :key="supervisor.id"
                :label="supervisor.name || supervisor.username"
                :value="supervisor.id"
            />
          </el-select>
        </el-form-item>

       
        <div class="task-create-section">
          <div class="section-header">
            <h3>Related Tasks</h3>
            <div class="button-group">
              <el-button type="primary" size="small" @click="openNewTaskDialog">
                <el-icon><Plus /></el-icon>Add Task
              </el-button>
            </div>
          </div>

          <el-table
              :data="projectForm.tasks"
              border
              style="width: 100%; margin-top: 15px;"
          >
            <el-table-column prop="title" label="Task Title" min-width="150" />
            <el-table-column prop="priority" label="Priority" width="100">
              <template #default="scope">
                <el-tag :type="getPriorityType(scope.row.priority)">
                  {{ scope.row.priority || 'Medium' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="endTime" label="Due Time" width="160" />
            <el-table-column label="Actions" width="150">
              <template #default="scope">
                <el-button type="warning" size="small" @click="editTask(scope.$index)">
                  <el-icon><Edit /></el-icon>Edit
                </el-button>
                <el-button type="danger" size="small" @click="removeTask(scope.$index)">
                  <el-icon><Delete /></el-icon>Delete
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div v-if="projectForm.tasks.length === 0" class="empty-tasks-tip">
            <el-empty description='No related tasks. Click "Add Task" to create' />
          </div>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="applyProjectDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="submitProjectApplication" :loading="submitting">Submit Application</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
        v-model="taskFormDialogVisible"
        :title="editingTaskIndex >= 0 ? 'Edit Task' : 'Add Task'"
        width="50%"
        destroy-on-close
    >
      <el-form
          ref="taskFormRef"
          :model="taskForm"
          :rules="taskRules"
          label-width="100px"
      >
        <el-form-item label="Task Title" prop="title" required>
          <el-input v-model="taskForm.title" placeholder="Please enter task title" />
        </el-form-item>
        <el-form-item label="Task Description" prop="description">
          <el-input
              v-model="taskForm.description"
              placeholder="Please enter task description"
              type="textarea"
              :rows="4"
          />
        </el-form-item>
        <el-form-item label="Priority" prop="priority">
          <el-select v-model="taskForm.priority" placeholder="Please select priority">
            <el-option label="High" value="High" />
            <el-option label="Medium" value="Medium" />
            <el-option label="Low" value="Low" />
          </el-select>
        </el-form-item>
        <el-form-item label="Time Range" prop="timeRange">
          <div style="display: flex; gap: 10px; align-items: center;">
            <el-date-picker
                v-model="taskForm.startTime"
                type="datetime"
                placeholder="Start Time"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="new Date(2000, 0, 1, 9, 0, 0)"
                style="width: 100%;"
                :disabled-date="disablePastDates"
                @change="validateTaskTimeRange"
            />
            <span>to</span>
            <el-date-picker
                v-model="taskForm.endTime"
                type="datetime"
                placeholder="End Time"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="new Date(2000, 0, 1, 18, 0, 0)"
                style="width: 100%;"
                :disabled-date="disableBeforeTaskStartDate"
                @change="validateTaskTimeRange"
            />
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="taskFormDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="submitTaskForm">Confirm</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue';
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus';
import { View, Edit, UploadFilled, Delete, Plus, ChatDotRound, Check, Close } from '@element-plus/icons-vue';
import { Project, getStudentProjects, applyForProject, getMyProjectEvaluation, ProjectEvaluation } from '../../api/project';
import { Task, getProjectTasks, getMyTaskDetail, updateTaskCompletionStatus, updateTaskStatus as updateTaskStatusApi } from '../../api/task';
import { TaskSubmission, getTaskSubmissions, deleteSubmission as apiDeleteSubmission, submitTaskFile } from '../../api/task';
import { getSupervisors } from '../../api/supervisor';
import { useUserStore } from '../../stores/user';
import type { FormInstance, FormRules } from 'element-plus';
import { useRouter } from 'vue-router';

// Add user store to get the current user ID
const userStore = useUserStore();

// Router instance
const router = useRouter();

// Data state
const projects = ref<Project[]>([]);
const loading = ref<boolean>(false);
const searchQuery = ref<string>('');

// Pagination settings
const currentPage = ref<number>(1);
const pageSize = ref<number>(10);
const totalProjects = ref<number>(0);

// Project details
const detailsDialogVisible = ref<boolean>(false);
const currentProject = ref<Project | null>(null);
const projectTasks = ref<Task[]>([]);
const tasksLoading = ref<boolean>(false);
const tasksLoadError = ref<string | null>(null);

// Task details
const taskDialogVisible = ref<boolean>(false);
const currentTask = ref<Task | null>(null);
const submissions = ref<TaskSubmission[]>([]);

// Upload file dialog
const uploadDialogVisible = ref<boolean>(false);

// Upload file related
const uploadHeaders = reactive({
  'Authorization': `Bearer ${localStorage.getItem('token')}`
});

// Apply for project related
const applyProjectDialogVisible = ref<boolean>(false);
const projectFormRef = ref<FormInstance>();
const submitting = ref<boolean>(false);
const supervisors = ref<any[]>([]);

// New: Form related
const taskFormDialogVisible = ref<boolean>(false);
const taskFormRef = ref<FormInstance>();
const editingTaskIndex = ref<number>(-1);

// Task form
const taskForm = ref({
  title: '',
  description: '',
  priority: 'Medium',
  status: 'Not Started',
  startTime: '',
  endTime: '',
});

// Task form validation rules
const taskRules = reactive<FormRules>({
  title: [{ required: true, message: 'Please enter the task title', trigger: 'blur' }],
  endTime: [{ required: true, message: 'Please select a due date', trigger: 'change' }],
});

// Apply for project form
const projectForm = ref({
  title: '',
  description: '',
  category: '',
  requirements: '',
  resources: '',
  startTime: '',
  endTime: '',
  supervisorId: null as number | null,
  tasks: [] as any[]
});

// Apply for project form validation rules
const projectRules = reactive<FormRules>({
  title: [{ required: true, message: 'Please enter the project title', trigger: 'blur' }],
  supervisorId: [{ required: true, message: 'Please select a supervisor', trigger: 'change' }],
  startTime: [{ required: true, message: 'Please select a start time', trigger: 'change' }],
  endTime: [{ required: true, message: 'Please select an end time', trigger: 'change' }],
});

// Add evaluation related state
const currentEvaluation = ref<ProjectEvaluation | null>(null);
const evaluationLoading = ref<boolean>(false);

// Add a reactive reference for table key
const tableKey = ref(0);

// Filter projects
const filteredProjects = computed(() => {
  let result = projects.value;

  // Search filter
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(project =>
        project.title.toLowerCase().includes(query) ||
        (project.description && project.description.toLowerCase().includes(query))
    );
  }

  // Update total for pagination
  totalProjects.value = result.length;
  
  // Pagination
  const start = (currentPage.value - 1) * pageSize.value;
  const end = Math.min(start + pageSize.value, result.length);
  
  console.log(`Pagination: page ${currentPage.value}, size ${pageSize.value}, showing ${start + 1}-${end} of ${totalProjects.value}`);

  return result.slice(start, end);
});

// Initialize data
onMounted(() => {
  fetchProjects();
  fetchSupervisors();
});

// Get projects
const fetchProjects = async () => {
  loading.value = true;
  try {
    const result = await getStudentProjects();
    
    // Calculate completion percentage for each project
    for (const project of result) {
      project.completionPercentage = calculateProjectCompletionPercentage(project);
    }
    
    // Sort projects by completion percentage in descending order (highest completion first)
    result.sort((a, b) => b.completionPercentage - a.completionPercentage);
    
    projects.value = result;

    // If there are projects, preload the task data for the first project
    if (result.length > 0) {
      preloadProjectTasks(result[0].id);
    }
  } catch (error) {
    console.error('Failed to retrieve projects:', error);
    ElMessage.error('Failed to retrieve projects');
  } finally {
    loading.value = false;
  }
};

// Preload project tasks to improve user experience
const preloadProjectTasks = async (projectId) => {
  if (!projectId) return;

  try {
    console.log(`Preloading project task data, Project ID: ${projectId}`);
    // Do not display the loading status, load silently in the background
    await getProjectTasks(projectId);
  } catch (error) {
    // Do not display errors when preloading fails, only record logs
    console.warn('Failed to preload project tasks:', error);
  }
};

// Get supervisor list
const fetchSupervisors = async () => {
  try {
    const result = await getSupervisors();
    supervisors.value = result;
  } catch (error) {
    console.error('Failed to retrieve supervisor list:', error);
    ElMessage.error('Failed to retrieve supervisor list');
  }
};

// View project details
const viewProjectDetails = async (project: Project) => {
  try {
    console.log('Viewing project details for project:', project.id);
    
    // 先设置当前项目，以便用户可以立即看到基本信息
    currentProject.value = project;
    detailsDialogVisible.value = true;

    // 清除先前任务数据
    projectTasks.value = [];
    tasksLoadError.value = null;

    // 开始加载相关任务
    refreshProjectTasks();

    // 如果项目状态为"已完成"，加载项目评估
    if (project.status === 'Completed') {
      console.log('Project is completed, loading evaluation');
      await loadProjectEvaluation(project.id);
    }
  } catch (error) {
    console.error('Error viewing project details:', error);
    ElMessage.error('加载项目详情时出错，请稍后再试');
  }
};

// Refresh project tasks
const refreshProjectTasks = async () => {
  if (!currentProject.value || !currentProject.value.id) {
    console.warn('Cannot refresh tasks: No current project selected');
    return;
  }

  tasksLoading.value = true;
  tasksLoadError.value = null;
  
  try {
    const projectId = currentProject.value.id;
    console.log('Fetching tasks for project ID:', projectId);
    
    const tasks = await getProjectTasks(projectId);
    console.log('Retrieved project tasks:', tasks);
    
    if (Array.isArray(tasks)) {
      // 只有当任务是数组时才设置
      projectTasks.value = tasks;
      
      if (projectTasks.value.length > 0) {
        console.log(`Successfully loaded ${tasks.length} tasks for project ${projectId}`);
        
        // 检查是否有任务没有正确加载 (缺少必要字段)
        const tasksWithMissingInfo = projectTasks.value.filter(task => 
          !task.title || task.title.trim() === ''
        );
        
        if (tasksWithMissingInfo.length > 0) {
          console.warn('Some tasks have missing title information:', tasksWithMissingInfo);
        }
      } else {
        console.log('No tasks found for this project');
      }
    } else {
      console.error('Invalid tasks data returned from API:', tasks);
      projectTasks.value = [];
      tasksLoadError.value = '加载任务失败：数据格式无效';
    }
  } catch (error: any) {
    console.error('Failed to retrieve project tasks:', error);
    
    // 处理特定错误情况
    if (error.response && error.response.status === 404) {
      tasksLoadError.value = '找不到相关任务信息，可能是API配置有误';
    } else {
      tasksLoadError.value = error.message || '加载任务失败，请稍后再试';
    }
    
    projectTasks.value = [];
  } finally {
    tasksLoading.value = false;
  }
};

// Get project evaluation
const loadProjectEvaluation = async (projectId: number) => {
  try {
    evaluationLoading.value = true;
    const evaluation = await getMyProjectEvaluation(projectId);
    currentEvaluation.value = evaluation;
  } catch (error: any) {
    // Ignore 404 or no data errors, because the project may not have been evaluated yet
    if (!error.response || error.response.status !== 404) {
      console.error('Failed to retrieve project evaluation:', error);
    }
    currentEvaluation.value = null;
  } finally {
    evaluationLoading.value = false;
  }
};

// Get the style class corresponding to the score
const getScoreClass = (score: number): string => {
  if (score >= 90) return 'score-excellent';
  if (score >= 80) return 'score-good';
  if (score >= 70) return 'score-satisfactory';
  if (score >= 60) return 'score-pass';
  return 'score-fail';
};

// Get the color corresponding to the score
const getScoreColor = (score: number): string => {
  if (score >= 90) return '#67C23A';  // Green
  if (score >= 80) return '#85ce61';  // Light green
  if (score >= 70) return '#E6A23C';  // Yellow
  if (score >= 60) return '#F56C6C';  // Red
  return '#909399';  // Gray
};

// View task details
const viewTaskDetails = async (task: Task) => {
  // First determine whether it is assigned to the current user, if not, give a prompt
  if (!isTaskAssignedToMe(task)) {
    ElMessage({
      message: 'This task is not assigned to you, you can view the basic information but cannot submit files',
      type: 'warning',
      duration: 3000,
      showClose: true
    });
  }

  // Reset file list to avoid displaying files from the previous task
  submissions.value = [];

  try {
    // Get complete task details
    const taskDetail = await getMyTaskDetail(task.id);
    currentTask.value = taskDetail;
    taskDialogVisible.value = true;

    // Get task submission records
    if (isTaskAssignedToMe(task)) {
      try {
        const taskSubmissions = await getTaskSubmissions(task.id);
        submissions.value = taskSubmissions;
      } catch (error) {
        console.error('Failed to retrieve task submission records:', error);
        submissions.value = [];
      }
    } else {
      submissions.value = []; // Do not display submission records for tasks that are not assigned to the current user
    }
  } catch (error: any) {
    console.error('Failed to retrieve task details:', error);
    taskDialogVisible.value = false; // Ensure the dialog is closed
    currentTask.value = null; // Clear state

    // Optimize error prompts, providing friendly prompts for situations where you do not have permission to view
    if (error.data && error.data.message === 'No permission to view this task') {
      console.log('No permission to view this task');
      return [];
    }

    if (error.data && error.data.message === '无权查看该任务') {
      console.log('No permission to view this task');
      return [];
    }

    ElMessage({
      message: 'Failed to retrieve task details, please try again later',
      type: 'error',
      duration: 3000
    });

    // Optimize error prompts, providing friendly prompts for situations where you do not have permission to view
    if (error.data && error.data.message === 'No permission to view this task' || error.data && error.data.message === '无权查看该任务') {
      ElMessage({
        message: 'You do not have permission to view the detailed information of this task, this task may not be assigned to you',
        type: 'warning',
        duration: 3000,
        showClose: true
      });
    } else {
      ElMessage({
        message: 'Failed to retrieve task details, please try again later',
        type: 'error',
        duration: 3000
      });
    }
  }
};

// Upload task file
const uploadTaskFile = async (task: Task) => {
  // Check if project is in Review Rejected or Waiting for Review status
  if (currentProject.value && (currentProject.value.status === 'Review Rejected' || currentProject.value.status === 'Waiting for Review')) {
    ElMessage({
      message: `Cannot upload files for project in ${currentProject.value.status} status`,
      type: 'warning',
      duration: 3000,
      showClose: true
    });
    return;
  }

  // First determine whether it is assigned to the current user, if not, give a prompt and interrupt
  if (!isTaskAssignedToMe(task)) {
    ElMessage({
      message: 'You can only upload files for tasks assigned to yourself',
      type: 'warning',
      duration: 3000,
      showClose: true
    });
    return;
  }

  // Reset file list to avoid displaying files from the previous task
  submissions.value = [];

  try {
    // Get complete task details
    const taskDetail = await getMyTaskDetail(task.id);
    currentTask.value = taskDetail;
    uploadDialogVisible.value = true;

    // Get task submission records
    const submissionResult = await getTaskSubmissions(task.id);
    submissions.value = submissionResult;
  } catch (error: any) {
    console.error('Failed to retrieve task details:', error);
    uploadDialogVisible.value = false; // Ensure the dialog is closed
    currentTask.value = null; // Clear state

    if (error.data && error.data.message === '无权查看该任务') {
      console.log('No permission to view this task');
      return [];
    }

    if (error.data && error.data.message === 'No permission to view this task') {
      console.log('No permission to view this task');
      return [];
    }

    ElMessage({
      message: 'Failed to retrieve task details, please try again later',
      type: 'error',
      duration: 3000
    });

    // Optimize error prompts, providing friendly prompts for situations where you do not have permission to view
    if (error.data && error.data.message === 'No permission to view this task' || error.data && error.data.message === '无权查看该任务') {
      ElMessage({
        message: 'You do not have permission to view the detailed information of this task, this task may not be assigned to you',
        type: 'warning',
        duration: 3000,
        showClose: true
      });
    } else {
      ElMessage({
        message: 'Failed to retrieve task details, please try again later',
        type: 'error',
        duration: 3000
      });
    }
  }
};

// Handle search
const handleSearch = () => {
  currentPage.value = 1;
};

// Handle page number change
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
};

// Handle page size change
const handleSizeChange = (size: number) => {
  console.log('Page size changed from', pageSize.value, 'to', size);
  pageSize.value = size;
  currentPage.value = 1; // Reset to first page when changing page size
  
  // Force update by creating a new array
  if (projects.value.length > 0) {
    projects.value = [...projects.value];
  }
  
  // Force table re-render
  tableKey.value += 1;
  
  console.log('Updated pageSize:', pageSize.value);
  console.log('Updated currentPage:', currentPage.value);
  console.log('Total projects:', totalProjects.value);
};

// Helper functions
const getStatusType = (status: string): 'primary' | 'success' | 'warning' | 'danger' | 'info' => {
  switch (status) {
    case 'Not Started': return 'info';
    case 'In Progress': return 'primary';
    case 'Waiting for Review': return 'warning';
    case 'Completed': return 'success';
    case 'Closed': return 'success';
    case 'Finalized': return 'success';
    case 'Pending Review': return 'warning';
    case 'Review Rejected': return 'danger';
    default: return 'info';
  }
};

const getTaskStatusType = (status: string): 'primary' | 'success' | 'warning' | 'danger' => {
  switch (status) {
    case 'Draft': return 'primary';
    case 'Midterm': return 'warning';
    case 'Final': return 'success';
    default: return 'primary';
  }
};

const getPriorityType = (priority: string): 'primary' | 'success' | 'warning' | 'danger' => {
  switch (priority) {
    case 'High': return 'danger';
    case 'Medium': return 'warning';
    case 'Low': return 'success';
    default: return 'warning';
  }
};

// Determine whether the task is assigned to the current user
const isTaskAssignedToMe = (task: Task): boolean => {
  if (!task) return false;
  
  // 确保用户已登录
  if (!userStore || !userStore.user || !userStore.user.id) {
    console.warn('User information not available');
    return false;
  }
  
  // 获取当前用户ID
  const currentUserId = userStore.user.id;
  
  // 检查任务是否有分配信息
  if (!task.assigneeId) {
    // 记录缺少分配信息的任务
    console.debug('Task has no assignee:', task);
    return false;
  }
  
  return task.assigneeId === currentUserId;
};

// Download submission file
const downloadSubmission = (submission: any) => {
  try {
    console.log('Starting to download file:', submission);

    // Get authorization token
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.error('Authorization expired, please log in again');
      return;
    }
    
    // Show downloading tip
    const loadingInstance = ElLoading.service({
      lock: true,
      text: 'Preparing to download file...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    // Single reliable method using Fetch API with proper headers
    fetch(`/api/user/submissions/${submission.id}/download`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    .then(response => {
      // Close loading animation
      loadingInstance.close();
      
      if (!response.ok) {
        if (response.status === 404) {
          throw new Error('File does not exist or has been deleted');
        } else if (response.status === 403) {
          throw new Error('You do not have permission to download this file');
        } else if (response.status === 401) {
          throw new Error('Authorization expired, please log in again');
        } else {
          throw new Error(`Download failed: ${response.status}`);
        }
      }
      
      return response.blob();
    })
    .then(blob => {
      // Create download link for the blob
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = submission.originalFilename;
      document.body.appendChild(link);
      link.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(link);
      
      ElMessage.success('File downloaded successfully');
    })
    .catch(error => {
      loadingInstance.close();
      console.error('Failed to download file:', error);
      
      // Show user-friendly error message
      ElMessageBox.alert(
        `Failed to download file "${submission.originalFilename}": ${error.message}`, 
        'Download Error', 
        {
          confirmButtonText: 'OK',
          type: 'error'
        }
      );
    });
  } catch (error) {
    console.error('Download file operation failed:', error);
    ElMessage.error('Failed to download file');
  }
};

// Open apply for project dialog
const openApplyProjectDialog = () => {
  // Reset form
  projectForm.value = {
    title: '',
    description: '',
    category: '',
    requirements: '',
    resources: '',
    supervisorId: null,
    tasks: []
  };

  // Load supervisor list
  fetchSupervisors();

  // Show dialog
  applyProjectDialogVisible.value = true;
};

// Open add task dialog
const openNewTaskDialog = () => {
  // Reset task form
  taskForm.value = {
    title: '',
    description: '',
    priority: 'Medium',
    status: 'Not Started',
    startTime: '',
    endTime: '',
  };
  editingTaskIndex.value = -1;
  taskFormDialogVisible.value = true;
};

// Edit task
const editTask = (index: number) => {
  const task = projectForm.value.tasks[index];
  taskForm.value = { ...task };
  editingTaskIndex.value = index;
  taskFormDialogVisible.value = true;
};

// Submit task form
const submitTaskForm = () => {
  // 手动验证标题是否为空
  if (!taskForm.value.title || taskForm.value.title.trim() === '') {
    ElMessage.warning('Please enter the task title');
    return;
  }
  
  taskFormRef.value?.validate((valid) => {
    if (valid) {
      // 确保status始终为Not Started
      taskForm.value.status = 'Not Started';
      
      if (editingTaskIndex.value >= 0) {
        // Update existing task
        projectForm.value.tasks[editingTaskIndex.value] = { ...taskForm.value };
      } else {
        // Add new task
        projectForm.value.tasks.push({ ...taskForm.value });
      }
      taskFormDialogVisible.value = false;
    }
  });
};

// Remove task
const removeTask = (index: number) => {
  projectForm.value.tasks.splice(index, 1);
};

// Submit project application
const submitProjectApplication = async () => {
  projectFormRef.value?.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        // Ensure that tasks are related to the supervisor
        const projectData = { ...projectForm.value };
        
        // 确保项目状态始终为Not Started
        projectData.status = 'Not Started';

        // Ensure that tasks have the necessary association information
        if (projectData.tasks) {
          projectData.tasks = projectData.tasks.map(task => ({
            ...task,
            supervisorId: projectData.supervisorId,
            status: 'Not Started', // 确保所有任务状态为Not Started
            // Default start time if not set
            startTime: task.startTime || new Date().toISOString()
          }));
        }

        const result = await applyForProject(projectData);
        ElMessage.success('Project application submitted, please wait for supervisor review');
        applyProjectDialogVisible.value = false;

        // Reset form
        projectForm.value = {
          title: '',
          description: '',
          category: '',
          requirements: '',
          resources: '',
          supervisorId: null,
          tasks: []
        };

        // Refresh project list
        fetchProjects();
      } catch (error: any) {
        console.error('Failed to apply for project:', error);
        ElMessage.error(error.data?.message || 'Failed to apply for project, please try again');
      } finally {
        submitting.value = false;
      }
    }
  });
};

// Auxiliary function: Calculate the task progress status
const getTaskProgressStatus = (task: Task) => {
  if (!task) return 'Not Started';
  
  // 检查任务是否有提交文件
  const hasSubmission = task.submissionCount && task.submissionCount > 0;
  
  // 根据提交和状态判断
  if (task.status === 'Completed' || task.completed) {
    return 'Completed';
  } else if (hasSubmission) {
    return 'Completed';
  } else {
    return 'Not Started';
  }
};

// Auxiliary function: Get the style type corresponding to the task progress status
const getTaskProgressType = (task: Task): 'success' | 'warning' | 'info' | 'danger' | 'primary' => {
  if (!task) return 'info';
  
  const status = getTaskProgressStatus(task);
  switch (status) {
    case 'Completed': return 'success';
    case 'Not Started': return 'info';
    default: return 'info';
  }
};

// Auxiliary function: Calculate the task completion percentage
const calculateTaskProgress = (task: Task) => {
  if (!task) return 0;
  
  // 如果任务已完成或有提交，返回100%
  if (task.completed || task.status === 'Completed' || 
      (task.submissionCount && task.submissionCount > 0)) {
    return 100;
  }
  
  // 如果当前正在查看任务详情，并且有提交记录，返回100%
  if (submissions.value && submissions.value.length > 0 &&
      currentTask.value && currentTask.value.id === task.id) {
    return 100;
  }
  
  // 如果没有上述情况，返回0%
  return 0;
};

// Navigate to chat function
const navigateToChat = () => {
  // Implement navigation to chat functionality
  router.push('/chat');
};

// Add handleProjectDialogClosed function to clean up resources when the project dialog is closed
const handleProjectDialogClosed = () => {
  // Clean up resources
  projectTasks.value = [];
  currentProject.value = null;
  tasksLoadError.value = null;
};

// File upload related functions
// File validation before upload
const beforeUpload = (file: File) => {
  const isLt50M = file.size / 1024 / 1024 < 50;

  if (!isLt50M) {
    ElMessage.error('File size cannot exceed 50MB!');
    return false;
  }

  return true;
};

// Handle file upload success
const handleUploadSuccess = async (response: any, file: any) => {
  ElMessage.success('文件上传成功，任务已提交并等待导师审核');

  // Add to submission list
  submissions.value.push(response);

  // Re-fetch task details to get latest status
  try {
    if (currentTask.value) {
      const updatedTask = await getMyTaskDetail(currentTask.value.id);

      // Update local task and current task
      currentTask.value = updatedTask;

      // Update task list
      const index = projectTasks.value.findIndex(t => t.id === updatedTask.id);
      if (index !== -1) {
        projectTasks.value[index] = updatedTask;
      }
      
      // Refresh project tasks to get latest status
      if (currentProject.value) {
        await refreshProjectTasks();
        
        // Also refresh the project list to update project status
        await fetchProjects();
      }
    }
  } catch (error) {
    console.error('Failed to retrieve updated task details:', error);
  }
};

// Handle file upload error
const handleUploadError = (error: any) => {
  console.error('Upload failed:', error);
  ElMessage.error('File upload failed');
};

// Handle delete submission
const handleDeleteSubmission = async (submission: any) => {
  try {
    await apiDeleteSubmission(submission.id);

    // Update submission list
    submissions.value = submissions.value.filter(s => s.id !== submission.id);

    ElMessage.success('Submission record deleted');
    
    // Refresh project tasks and project list to update status
    if (currentProject.value) {
      await refreshProjectTasks();
      await fetchProjects();
    }
  } catch (error) {
    console.error('Failed to delete submission record:', error);
    ElMessage.error('Failed to delete submission record');
  }
};

// Format file size
const formatFileSize = (size: number): string => {
  if (size < 1024) {
    return size + 'B';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + 'KB';
  } else {
    return (size / 1024 / 1024).toFixed(2) + 'MB';
  }
};

// Add status translation function
const translateStatus = (status: string) => {
  const translations = {
    '未开始': 'Not Started',
    '进行中': 'In Progress',
    '已完成': 'Completed',
    '已结项': 'Finalized',
    '未审核': 'Pending Review',
    '审核未通过': 'Review Failed',
    '待批阅': 'Waiting for Review',
    '初稿': 'Draft',
    '期中': 'Midterm',
    '终稿': 'Final',
    '高': 'High',
    '中': 'Medium',
    '低': 'Low'
  };
  
  return translations[status] || status;
};

// Add hasEvaluation function
const hasEvaluation = (task: Task): boolean => {
  return currentEvaluation.value !== null;
};

// Calculate project completion percentage based on task completion
const calculateProjectCompletionPercentage = (project) => {
  // If the project status is 'Completed', it's 100% complete
  if (project.status === 'Completed') {
    return 100;
  }
  
  // If the project is 'Not Started', it's 0% complete
  if (project.status === 'Not Started') {
    return 0;
  }
  
  // For 'In Progress' projects, calculate based on task completion
  if (project.completedTaskCount !== undefined && project.totalTaskCount !== undefined) {
    return project.totalTaskCount > 0 
      ? (project.completedTaskCount / project.totalTaskCount) * 100 
      : 0;
  }
  
  // Default percentages for different statuses if task counts aren't available
  switch (project.status) {
    case 'In Progress': return 50;
    case 'Waiting for Review': return 90;
    case 'Pending Review': return 80;
    case 'Finalized': return 100;
    default: return 25;
  }
};


const disablePastDates = (time) => {

  return time.getTime() < Date.now() - 8.64e7; // 8.64e7 是一天的毫秒数，允许选择今天
};


const disableBeforeProjectStartDate = (time) => {
  const now = Date.now() - 8.64e7; 
  

  if (!projectForm.value.startTime) {
    return time.getTime() < now;
  }
  
  const startDateTime = new Date(projectForm.value.startTime).getTime();
  return time.getTime() < startDateTime || time.getTime() < now;
};


const disableBeforeTaskStartDate = (time) => {
  const now = Date.now() - 8.64e7;
  
  if (!taskForm.value.startTime) {
    return time.getTime() < now;
  }
  
  const startDateTime = new Date(taskForm.value.startTime).getTime();
  return time.getTime() < startDateTime || time.getTime() < now;
};

const updateTaskStatus = async (taskId, status) => {
  try {
    await updateTaskStatusApi(taskId, { status: status });
    console.log(`Task ${taskId} status updated to ${status}`);
  } catch (error) {
    console.error(`Failed to update task ${taskId} status:`, error);
  }
};

// Fetch project tasks
const fetchProjectTasks = async (projectId) => {
  tasksLoading.value = true;
  try {
    const data = await getProjectTasks(projectId);
    
    if (data && data.length > 0) {
      data.sort((a, b) => {
        if (a.endTime && b.endTime) {
          return new Date(a.endTime) - new Date(b.endTime); 
        } else if (a.endTime) {
          return -1; 
        } else if (b.endTime) {
          return 1; 
        }
        return 0;
      });
      
      data.forEach(task => {
        if (task.endTime && task.status !== 'Completed') {
          const endDate = new Date(task.endTime);
          const now = new Date();
          if (endDate < now) {
            updateTaskStatus(task.id, 'Completed');
            task.status = 'Completed';
          }
        }
      });
    }
    
    projectTasks.value = data || [];
  } catch (error) {
    console.error('Failed to fetch project tasks:', error);
    ElMessage.error('Failed to retrieve project task information');
  } finally {
    tasksLoading.value = false;
  }
};

// Add validateProjectTimeRange function
const validateProjectTimeRange = () => {
  if (projectForm.value.startTime && projectForm.value.endTime) {
    const startTime = new Date(projectForm.value.startTime);
    const endTime = new Date(projectForm.value.endTime);
    
    if (endTime < startTime) {
      ElMessage.error('The end time cannot be earlier than the start time.')
      projectForm.value.endTime = null;
    }
  }
};

// Add validateTaskTimeRange function
const validateTaskTimeRange = () => {
  if (taskForm.value.startTime && taskForm.value.endTime) {
    const startTime = new Date(taskForm.value.startTime);
    const endTime = new Date(taskForm.value.endTime);
    
    if (endTime < startTime) {
      ElMessage.error('The end time cannot be earlier than the start time.')
      taskForm.value.endTime = null;
    }
  }
};
</script>
<style scoped>
.project-view {
  padding: 10px;
  height: calc(100vh - 60px); /* 设置高度为视口高度减去顶部导航栏高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
}

.box-card {
  margin-bottom: 10px;
  overflow-x: auto; /* Enable horizontal scrolling if needed */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  position: sticky;
  bottom: 0;
  background-color: #fff;
  padding: 5px 0;
  z-index: 1;
}

.project-description,
.project-requirements,
.project-resources,
.task-description {
  white-space: pre-wrap;
  max-height: 200px;
  overflow-y: auto;
}

.related-tasks,
.file-upload-section,
.submission-list {
  margin-top: 20px;
}

.upload-centered {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.task-info-summary {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

h3 {
  margin-bottom: 15px;
  font-weight: 500;
  color: #303133;
}

.sub-text {
  font-size: 0.9em;
  color: #909399;
  margin-top: 5px;
}

.empty-data {
  padding: 30px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.task-item {
  margin-bottom: 15px;
  padding: 15px;
  border: 1px dashed #e0e0e0;
  border-radius: 4px;
  background-color: rgba(64, 158, 255, 0.05);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.task-header h4 {
  margin: 0;
  color: #409EFF;
}

.add-task-button {
  margin-top: 20px;
  text-align: center;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.task-completion-controls {
  margin-right: 15px;
}

.loading-container {
  padding: 20px;
  text-align: center;
}

.error-container {
  padding: 20px;
  text-align: center;
}

.empty-task {
  padding: 20px;
  text-align: center;
}

/* Task section styles */
.task-create-section {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.button-group {
  display: flex;
  gap: 10px;
}

.empty-tasks-tip {
  margin: 20px 0;
  text-align: center;
}

/* Evaluation related styles */
.project-evaluation-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
}

.score-container {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 20px;
  text-align: center;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.score-value {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 5px;
}

.score-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.score-progress {
  margin-top: 10px;
}

.score-excellent {
  background-color: #f0f9eb;
  color: #67C23A;
}

.score-good {
  background-color: #f0f9eb;
  color: #85ce61;
}

.score-satisfactory {
  background-color: #fdf6ec;
  color: #E6A23C;
}

.score-pass {
  background-color: #fef0f0;
  color: #F56C6C;
}

.score-fail {
  background-color: #f4f4f5;
  color: #909399;
}

.comment-card {
  height: 100%;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.comment-content {
  min-height: 80px;
  white-space: pre-line;
}

.evaluator-info {
  margin-top: 15px;
  text-align: right;
}

.evaluation-container {
  margin-top: 15px;
}

/* Ensure tables can scroll horizontally */
.el-table {
  width: 100%;
  overflow-x: auto;
}

.progress-icon-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.progress-icon {
  font-size: 20px;
}
</style> 